#!/usr/bin/env python
#!coding=utf-8

from os import getpid
import wx
import wx.xrc

from greecket import wxfactory


class frm1(wx.Frame):
    def __init__(self,parent,*args,**kargs):
        wx.Frame.__init__(self,parent,-1,'MyChat',size=(465,380))
        gui=wx.xrc.XmlResource('gui.xrc')
        self.p1=gui.LoadPanel(self,'p1')
        self.LoadNames(self)
        self._sckp=wxfactory.Factory(self,('localhost',5423))
        self._gfc=self._sckp.getGreecket()
        self.Bind(wxfactory.EVT_GREE_DATARECEIVED,self.OnDataReceived)
        self.Bind(wxfactory.EVT_GREE_CONNECTIONMADE,self._connectionMade)
        self.Bind(wxfactory.EVT_GREE_CONNECTIONLOST,self.OnConnectionLost)
        self.Bind(wxfactory.EVT_GREE_LISTEN,self.OnListen)
        self.Bind(wxfactory.EVT_GREE_ERROR,self._socketerror)
        self.Bind(wx.EVT_BUTTON,self.OnbtRunClick,self.btRun)
        self.Bind(wx.EVT_BUTTON,self.OnbtSend,self.btSend)
        self.Bind(wx.EVT_CLOSE,self.OnExit,self)

    def LoadNames(self,ctl):
        n=ctl.GetName()
        self.__dict__[n]=ctl
        if hasattr(ctl,'Children'):
            for c in ctl.Children:
                self.LoadNames(c)

    def OnDataReceived(self,evt):
        self.txAll.WriteText('>>: %s\n' % (evt.Data.decode('utf-8','replace')))
        

    def OnConnectionLost(self,evt):
        self.txAll.WriteText('--: %s:%s\n' % (evt.Data))
                
    def OnListen(self,evt):
        self.txAll.WriteText('==: %s.\n' % str(evt))

    def doRun(self,AsServer):
        d=(self.edHost.Value,int(self.edPort.Value))
        if AsServer:
            self._sckp.listen(d)
        else:
            self._sckp.connect(d)
        if not self._sckp.isRunning():
            self._sckp.start()

    def OnbtRunClick(self,evt):
        self.doRun(self.ckbIsSrv.IsChecked())
        evt.Skip()

    def OnbtSend(self,evt):
        self._gfc.send(self.txtInput.Value.encode('utf-8','replace'))
        print 'send data'
        self.txAll.WriteText('<<: %s\n' % (self.txtInput.Value))
        self.txtInput.Value=''
        evt.Skip()

    def OnExit(self,evt):
        self.txAll.WriteText('**: Exit\n')
        self._sckp.stop()
        evt.Skip()

    def _connectionMade(self,evt):
        h,a=evt[1].getPeerName()
        self.txAll.WriteText('++: %s:%s\n' % (h,a))

    def _socketerror(self,evt):
        self.txAll.WriteText('**: %s.\n' % evt.Data)


def main(*args,**kwargs):
    app=wx.PySimpleApp()
    frm=frm1(None,args,kwargs)
    frm.Show()
    app.MainLoop()

if __name__=='__main__':
    main()
